package com.moonshineproject.plugin.haxe.haxeproject.exporter
{
	import com.moonshineproject.plugin.haxe.haxeproject.vo.HaXeProjectVO;
	import com.moonshineproject.utils.FileUtil;
	import com.moonshineproject.utils.Utils;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	public class HaxeFlashDevelopExporter
	{
		public static function export(p:HaXeProjectVO, file:File):void
		{
			if (!file.exists) FileUtil.createFile(file);
			
			var output:XML = toXML(p);
			
			var fw:FileStream = new FileStream();
			
			fw.open(file, FileMode.WRITE);
			// Does not prefix with a 16-bit length word like writeUTF() does
			fw.writeUTFBytes('<?xml version="1.0" encoding="utf-8"?>\n' + output.toXMLString());
			fw.close();
		}
		
		/*
			Serialize to FlashDevelop compatible XML project file.
		*/
		private static function toXML(p:HaXeProjectVO):XML
		{
			var project:XML = <project></project>;
			
			// Get output node with relative paths		
			project.appendChild(p.swfOutput.toXML(p.folder));
			
			project.appendChild(exportPaths(p.classpaths, <classpaths/>, <class/>, p));
			
			project.appendChild(p.buildOptions.toXML());
			
			project.appendChild(exportPaths(p.haxelib, <haxelib/>, <library/>, p, "name"));
			
			project.appendChild(p.assetLibrary);
			project.appendChild(exportPaths(p.targets, <compileTargets/>, <compile/>, p));
			
			var prebuildXML:XML = <preBuildCommand/>;
			prebuildXML.appendChild(p.prebuildCommands);
			project.appendChild(prebuildXML);
			
			var postbuildXML:XML = <postBuildCommand/>;
			postbuildXML.appendChild(p.postbuildCommands);
			postbuildXML.@alwaysRun = Utils.serializeBoolean(p.postbuildAlways);
			project.appendChild(postbuildXML);
			
			var options:XML = <options/>;
			var optionPairs:Object = {
				showHiddenPaths		:	Utils.serializeBoolean(p.showHiddenPaths),
				testMovie			:	Utils.serializeString(p.testMovie)
			}
			if (p.testMovieCommand && p.testMovieCommand != "") 
			{
				optionPairs.testMovieCommand = p.testMovieCommand;
			}
			options.appendChild(Utils.serializePairs(optionPairs, <option/>));
			project.appendChild(options);
				
			return project;
		}
		
		private static function exportPaths(v:Vector.<File>, container:XML, element:XML, p:HaXeProjectVO, attrib:String="path"):XML
		{
			for each (var f:File in v) 
			{
				var e:XML = element.copy();
				var relative:String = p.folder.getRelativePath(f);
				e['@'+attrib] = relative ? relative : f.nativePath;
				container.appendChild(e);
			}
			return container;
		}
		
	}
}